<template>
  <page-layout>
    <a-spin :spinning="isLoading">
      <a-card>
        <footer-button :buttons="state.buttons" />
        <a-form>
          <a-row type="flex" justify="space-between">
            <a-col
              :span="7"
              v-for="item in baseFields.fields"
              :key="item.field"
            >
              <a-form-item :label="item.title" class="mb-5">
                {{ handleFormEmptyData(baseFields.data[item.field]) }}
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <a-tabs :active-key(v-model)="activeKey" size="small">
          <a-tab-pane key="detail" :tab="t('button.detail')">
            <DetailBaseForm
              :data="baseFields.data"
              :types="{ commisType: state.commisType }"
            />
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </a-spin>
    <a-modal
      :visible="state.modalVisible"
      v-if="state.modalVisible"
      :title="t('button.generateQrCode')"
      :cancelText="t('button.cancel')"
      :okText="t('button.downloadQrCode')"
      @ok="handleOk"
      @cancel="cancel">
      <div class="qrcode">
        <img :src="state.qrCodeUrl" alt="二维码">
        <!-- <qrcode-vue :value="state.qrCodeUrl" :size="200" level="H" /> -->
      </div>
    </a-modal>
  </page-layout>
</template>
<script>
export default {
  name: "channel-manage-detail"
}
</script>
<script setup>
import { reactive, onActivated, createVNode, ref } from "vue";
import { message, modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { useRoute, useRouter } from "vue-router";
import { handleFormEmptyData } from "@/tools/filters";
import { downloadIamge } from "@/tools/common";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import dictEnum from "@/const/dict";
import { isEmpty } from "@/tools/common";
import DetailBaseForm from "./components/detail-base-form";
import { details, update, mkurl } from "@/api/module/channel-manage";
import QrcodeVue from 'qrcode.vue'
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const isLoading = ref(false);
const state = reactive({
  modalVisible: false,
  qrCodeUrl: "https://crmh5.lightcourse.com/#/bindasbusiness",
  buttons: [
    {
      name: "generateQrCode",
      event: () => handleQrCode(),
      type: "primary",
      code: "",
    },
    {
      name: "enterBasicRewards",
      event: () => handleRewards(),
      type: "primary",
      code: "",
    },
    {
      name: "initiatePaymentApplication",
      event: () => handleApp(),
      type: "primary",
      code: "",
    },
    {
      name: "endCooperation",
      event: () => handleCooper(),
      type: "primary",
      code: "",
    },
  ],
  commisType: 0,
});

const handleQrCode = async() => {
  const result = route.query;
  if (!result || !result.id) return;
  const { data, success } = await mkurl({id: result.id})
  if (success) {
    state.qrCodeUrl = data;
    state.modalVisible = true
  }
};
const handleRewards = () => {};
const handleApp = () => {};
const handleOk = () => {
  downloadIamge(state.qrCodeUrl, baseFields.data.chnHead)
}
const cancel = () => {
  state.modalVisible = false
}
const handleCooper = () => {
  if (baseFields.data.id) {
    modal.confirm({
    title: `${t('channelManage.label.AreYouSureToEndThePartnership')}?`,
    icon: createVNode(ExclamationCircleOutlined),
    okText: t('button.determine'),
    cancelText: t('button.cancel'),
    onOk() {
      update({id: baseFields.data.id, chnTradeStatus: 2 })
        .then((res) => {
          if (res.success) {
            message.success({ content: t('message.operationSucceeded'), duration: 1 }).then(() => {
              router.push({
                path: "/market/channel-manage",
              });
            });
          } else {
            message.warning({ content: t('message.operationFailed'), duration: 1 });
          }
        })
        .catch((err) => {
          console.log("err: ", err);
          message.warning({ content: t('message.operationFailed'), duration: 1 });
        });
      }
    })
  }
};

const baseFields = reactive({
  fields: [
    { title: t('channelManage.label.channelType'), field: "chnType" },
    { title: t('channelManage.label.channelName'), field: "chnName" },
    { title: t('channelManage.label.channelLeader'), field: "chnHead" },
    { title: t('channelManage.label.channelSaleHead'), field: "saleHead" },
    { title: t('channelManage.label.responsibleSchool'), field: "chargeSchool" },
    { title: t('channelManage.label.cooperationStatus'), field: "chnTradeStatus" },
    { title: t('channelManage.label.cooperationStartTime'), field: "beginTime" },
    { title: t('label.creator'), field: "createBy" },
    { title: t('label.creationTime'), field: "createTime" },
    { title: t('channelManage.label.state'), field: "chnStatus" },
  ],
  data: {},
  dict: {},
});
const getDataByDict = (data, dictKey) => {
  if (isEmpty(data)) return "-";
  const item = baseFields.dict[dictKey].find((v) => v.value == data);
  if (isEmpty(item)) return "-";
  return item.label;
};

onActivated(async () => {
  const result = route.query;
  if (!result || !result.id) return;
  baseFields.dict = await getDictByCodesReturnObj([
    dictEnum.CHANNEL_TYPE,
    dictEnum.DOCUMENT_TYPE,
    dictEnum.CALCULATION_POINT,
    dictEnum.IN_AREA,
    dictEnum.COMMIS_TYPE,
    dictEnum.ZONE_CODE,
    dictEnum.CHN_STATUS,
    dictEnum.PARTNERSHIP,
  ]);

  isLoading.value = true;
  let res = await details({ id: result.id });
  if (res.code === 500) return message.error(t('message.failedToGetDetails'));

  state.commisType = res.data.commisType;
  let infoList = JSON.parse(res.data.commisInfo);
  res.data.rate = res.data.commisType == 0 
                  ? infoList[0] && infoList[0].rate ? `${infoList[0].rate}%`: ''
                  : ''
  let infoData = infoList.map((item, index) => {
    return {
      commisType:
        index == 0
          ? (res.data.commisType = getDataByDict(
              res.data.commisType,
              dictEnum.COMMIS_TYPE
            ))
          : "undefined",
      userNums: `${item.min}~${item.max}人`,
      rates: `${item.rate}%`,
    };
  });

  res.data.chnType = getDataByDict(res.data.chnType, dictEnum.CHANNEL_TYPE);
  res.data.papersType = getDataByDict(
    res.data.papersType,
    dictEnum.DOCUMENT_TYPE
  );
  res.data.perfmNode = getDataByDict(
    res.data.perfmNode,
    dictEnum.CALCULATION_POINT
  );
  res.data.belongsAdd = getDataByDict(res.data.belongsAdd, dictEnum.IN_AREA);
  res.data.zoneCode = getDataByDict(res.data.zoneCode, dictEnum.ZONE_CODE);
  res.data.chnTradeStatus = getDataByDict(
    res.data.chnTradeStatus,
    dictEnum.CHN_STATUS
  );
  res.data.chnStatus = getDataByDict(res.data.chnStatus, dictEnum.PARTNERSHIP);
  res.data.commisInfoList = infoData;
  res.data.bgppTrials =
    `${t('channelManage.label.probationReward')}：${res.data.bgppTrial || ''}${t('channelManage.label.Yuan/group')}` +
    " ~ " +
    `${t('channelManage.label.rewardAfterBecomingRegular')}：${res.data.bgppPositive || ''}${t('channelManage.label.Yuan/group')}`;
  res.data.collectTrials =
    `${t('channelManage.label.probationReward')}：${res.data.collectTrial || ''}${t('channelManage.label.Yuan/group')}` +
    " ~ " +
    `${t('channelManage.label.rewardAfterBecomingRegular')}：${res.data.collectPositive || ''}${t('channelManage.label.Yuan/group')}`;
  res.data.sponsorTrials =
    `${t('channelManage.label.probationReward')}：${res.data.sponsorTrial || ''}${t('channelManage.label.Yuan/group')}` +
    " ~ " +
    `${t('channelManage.label.rewardAfterBecomingRegular')}：${res.data.sponsorPositive || ''}${t('channelManage.label.Yuan/group')}`;
  res.data.pshowTrials =
    `${t('channelManage.label.probationReward')}：${res.data.pshowTrial || ''}${t('channelManage.label.Yuan/group')}` +
    " ~ " +
    `${t('channelManage.label.rewardAfterBecomingRegular')}：${res.data.pshowPositive || ''}${t('channelManage.label.Yuan/group')}`;
  res.data.planTrials =
    `${t('channelManage.label.probationReward')}：${res.data.planTrial || ''}${t('channelManage.label.Yuan/group')}` +
    " ~ " +
    `${t('channelManage.label.rewardAfterBecomingRegular')}：${res.data.planPositive || ''}${t('channelManage.label.Yuan/group')}`;
  res.data.promoteTrials =
    `${t('channelManage.label.probationReward')}：${res.data.promoteTrial || ''}${t('channelManage.label.Yuan/group')}` +
    "~" +
    `${t('channelManage.label.rewardAfterBecomingRegular')}：${res.data.promotePositive || ''}${t('channelManage.label.Yuan/group')}`;
  baseFields.data = res.data;
  isLoading.value = false;
});
</script>

<style lang="scss" scoped>
.qrcode {
  width: 100%;
  display: flex;
  justify-content: center;
}
</style>